package com.example.moneygrosService;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class BluetoothHandler {
	private static final String TAG = BluetoothHandler.class.getSimpleName();

	public static final String MONEYGROS_BT_SERVICE_NAME = "MoneyGros-BT-Service";
	public static final UUID MONEYGROS_BT_SERVICE_UUID = UUID.fromString("3817600e-5ff4-45dc-924f-c8cb9f650320");

	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothServer mBluetoothServer;
	
	private List<ReadThread> mThreadList;
	
	private Context mContext;

	public BluetoothHandler(Context context) {
		super();
		// TODO Auto-generated constructor stub
		mContext=context;
		mThreadList = new LinkedList<ReadThread>();
		
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		Log.d(TAG, "contructor");
		
		setBluetooth();
		
		if(enabled()){
        	mBluetoothServer = new BluetoothServer(mBluetoothAdapter);
        	mBluetoothServer.start();
		} else {
			return;
		}
        
	}

	public boolean enabled(){
		if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()){
			return true;
		} else {
			return false;
		}
	}
	
	private void setBluetooth() {
		// TODO Auto-generated method stub
		if(mBluetoothAdapter == null){
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				// Device does not support Bluetooth
	    		Log.d(TAG, "Pas de bluetooth");
 
			} else {

				if (!mBluetoothAdapter.isEnabled()) {
		    		Log.d(TAG, "Bluetooth coupé");

					//				
					//				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					//				this.startActivity(enableBtIntent, REQUEST_ENABLE_BT);
				} else {

				}
			}
		}
	} 
	

	private class BluetoothServer extends Thread {
	    private final BluetoothServerSocket blueServerSocket;
	    private BluetoothAdapter mAdapter;
	    public BluetoothServer(BluetoothAdapter adapter) {
	        // On utilise un objet temporaire qui sera assigné plus tard à blueServerSocket car blueServerSocket est "final"
	    	mAdapter = adapter;
	    	
	    	BluetoothServerSocket tmp = null;
	        try {
				Log.d(TAG, "opening "+MONEYGROS_BT_SERVICE_NAME+ " server");

				// MON_UUID est l'UUID (comprenez identifiant serveur) de l'application. Cette valeur est nécessaire côté client également !
				tmp = adapter.listenUsingInsecureRfcommWithServiceRecord(MONEYGROS_BT_SERVICE_NAME, MONEYGROS_BT_SERVICE_UUID);
				Log.d(TAG, MONEYGROS_BT_SERVICE_NAME+" server "+ tmp.toString()+ " opened");

	        } catch (IOException e) { }
	        blueServerSocket = tmp; 
	    } 

	    public void run() {
			Log.d(TAG, "run'ing");
	    	if(blueServerSocket != null){
	    		BluetoothSocket blueSocket = null;
	    		// On attend une erreur ou une connexion entrante
	    		while (true) {
	    			try {
	    				Log.d(TAG, "waiting for connection");
	    				blueSocket = blueServerSocket.accept();
	    				Log.d(TAG, "socket opened "+blueSocket.toString());

	    				// faire un thread pour recevoir le message
	    				ReadThread thread = new ReadThread(blueSocket);
	    				thread.start();
	    				mThreadList.add(thread);
	    			} catch (IOException e) {
	    				break;
	    			}
	    			// Si une connexion est acceptée
	    			if (blueSocket != null) {
	    				// On fait ce qu'on veut de la connexion (dans un thread séparé), à vous de la créer
	    				//	                manageConnectedSocket(blueSocket);
	    				//	                blueServerSocket.close();
	    				
	    				// créer un thread de gestion de la socket
	    				
	    				
	    				break;
	    			}
	    		}
	    	}
	    }

	    // On stoppe l'écoute des connexions et on tue le thread
	    public void cancel() {
	        try {
	            blueServerSocket.close();
	        } catch (IOException e) { }
	    }
	}
	
	
    private class ReadThread extends Thread {	
    	private final String TAG = ReadThread.class.getSimpleName();

        private BluetoothSocket mSocket;

        public ReadThread(BluetoothSocket socket) {
            super();
            mSocket = socket;
        }

        @Override
        public void run() {
			Log.d(TAG, "run'ing");
			
        	try {
        		InputStream is = mSocket.getInputStream();

        		final byte data[] = new byte[8192];
        		try {
        			while(is.read(data) > -1) { 
	    				Log.d(TAG, "lecture de données "+data[0]);

	    				showNotification("lecture de données "+data[0]);
//	    				Toast.makeText(mContext, String.format("Msg BT reçu \"%s\" de  %s", String.valueOf(data[0]), mSocket.getRemoteDevice().getName()), Toast.LENGTH_LONG);
        				// At this point, the application can pass the raw data to a parser that
        				// has implemented the IEEE 11073-xxxxx specifications.  Instead, this sample
        				// simply indicates that some data has been received.
        				//                    sendMessage(STATUS_READ_DATA, 0);
        			}
        		} catch(IOException ioe) {}
        		if (is != null) {
        			try {
        				is.close();
        			} catch (IOException e) { /* Do nothing. */ }
        		}
        	} catch (IOException e1) {
        		// TODO Auto-generated catch block
        		try {
        			mSocket.close();
        		} catch (IOException e) { /* Do nothing. */ }
        		e1.printStackTrace();
        	}
//            sendMessage(STATUS_READ_DATA_DONE, 0);
        }
    }
	private void showNotification(String text) {
		NotificationManager nm = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);

		// Set the icon, scrolling text and timestamp
		Notification notification = new NotificationCompat.Builder(mContext)
			.setContentTitle(mContext.getText(R.string.notif_commService_label))
			.setContentText(text)
			.setTicker(text)
			.setSmallIcon(R.drawable.ic_launcher)
			.build();
		// The PendingIntent to launch our activity if the user selects this notification
		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, MainActivityService.class), 0);
	
		// Send the notification.
		// We use a layout id because it is a unique number.  We use it later to cancel.
//		nm.notify(R.string.notif_commService_started, notification);
		nm.notify(12, notification);
	}
}
